// pages/vip/chapter_exercise/chapter_exercise.js
const db = wx.cloud.database({});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    subject: [],
    index: 0,
    op_in: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
    //滑动坐标
    startX: 0,
    startY: 0,
    right: 0,
    error: 0,
    popup: false,
    checked: false,
    num: 0,
    radio: '',
    id:0,
  },


  //点击选项
  onChange(event) {
    let subject = this.data.subject
    let index = this.data.index

    this.setData({
      radio: event.detail,
      ['subject[' + index + '].user_answer[0]']: event.detail
    });
    console.log(event.target.id)
    let openId = wx.getStorageSync('openId')
    let _id = openId + '+' + event.target.id
    if (event.detail == subject[index].answer) {

      var right = true
      var error = false
      var errors = Number(this.data.error) + 1
      this.setData({
        error: errors,
        ['subject[' + index + '].error']: false,
        ['subject[' + index + '].right']: true
      })
      const _ = db.command
      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(5)
        }
      })
    } else {

      var rights = Number(this.data.right) + 1
      var error = true
      var right = false
      this.setData({
        right: rights,
        ['subject[' + index + '].error']: true,
        ['subject[' + index + '].right']: false
      })
      const _ = db.command
      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(2)
        }
      })
    }
    // 点击选项后上传
    db.collection('subject-all').doc(_id).set({
        data: {
          star: subject[index].star,
          analysis: subject[index].analysis,
          answer: subject[index].answer,
          chapters: subject[index].chapters,
          difficulty: subject[index].difficulty,
          details: subject[index].details,
          option: subject[index].option,
          subject: subject[index].subject,
          title: subject[index].title,
          type: subject[index].type,
          user_answer: Array(event.detail),
          right: right,
          error: error
        },
      })
      .then(res => {

        console.log('上传用户答案')
      })
  },


  // 双选部分
  onChanges(event) {
    let index = this.data.index
    this.setData({
      ['subject[' + index + '].user_answer']: event.detail,
    });


  },
  arrayEqual: function (user_answer, answer) {
    //先将数组排序
    user_answer = user_answer.sort();
    answer = answer.sort();
    //判断数组长度是否相等，若不相等返回false
    if (user_answer.length != answer.length)
      return false;
    //逐个比较数组元素
    for (var i = 0; i < user_answer.length; ++i) {
      if (user_answer[i] !== answer[i])
        return false;
    }
    return true;
  },
  sub() {
    let index = this.data.index
    let openId = wx.getStorageSync('openId')
    let _id = openId + '+' + this.data.subject[index]._id
    let user_answer = this.data.subject[index].user_answer
    let answer = this.data.subject[index].answer
    console.log(user_answer)
    if (this.arrayEqual(user_answer, answer) == true) {

      // var right = true
      // var error = false
      var errors = Number(this.data.error) + 1
      this.setData({
        error: errors,
        ['subject[' + index + '].error']: false,
        ['subject[' + index + '].right']: true
      })
      const _ = db.command

      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(5)
        }
      })
    } else {

      var rights = Number(this.data.right) + 1
      // var error = true
      // var right = false
      this.setData({
        right: rights,
        ['subject[' + index + '].error']: true,
        ['subject[' + index + '].right']: false
      })
      const _ = db.command
      db.collection('user').doc(openId).update({
        data: {
          user_integration: _.inc(2)
        }
      })
    }
    // 点击选项后上传
    let subject = this.data.subject
    db.collection('subject-all').doc(_id).set({
        data: {
          star: subject[index].star,
          analysis: subject[index].analysis,
          answer: subject[index].answer,
          chapters: subject[index].chapters,
          difficulty: subject[index].difficulty,
          details: subject[index].details,
          option: subject[index].option,
          subject: subject[index].subject,
          title: subject[index].title,
          type: subject[index].type,
          user_answer: user_answer,
          right: subject[index].right,
          error: subject[index].error
        },
      })
      .then(res => {

        console.log('上传用户答案')
      })
  },




  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  noop() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  
    

},


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options.id)
    this.setData({
     id:   options.id
    })
    //1.查openid
    var openId = wx.getStorageSync('openId')
    // 2.查科目
    db.collection("user").doc(openId).get()
      .then(res => {
        let user_default = Number(res.data.user_default)
        console.log(user_default)
    // 3.查题目数量及查所有题
     db.collection('subject').where({
      "subject": user_default
    }).count().then(res => {
      // resolve(res.total);
      // console.log(res.total)
      let id = this.data.id
      console.log(id)
      for (let i = 0; i < res.total; i += 100) {
        wx.cloud.callFunction({
            // 云函数名称
            name: 'getsubject',
            data: {
              num: i,
              subject: user_default,
              chapters:	Number(id)
            }
          })
          .then(res => {
            var subject = this.data.subject
            let subjects = subject.concat(res.result.data)
            this.setData({
              subject: subjects,
  
            })
          })
      }
 
      setTimeout(()=>
      {
        let subject = this.data.subject
        // console.log(subject)
        for (let list = 0; list < subject.length; list++) {
         let _id = subject[list]._id
          // console.log(_id)
         let openId = wx.getStorageSync('openId')
         let id = openId + '+' + _id
         var error = this.data.error
         var right = this.data.right
         db.collection('subject-all').doc(id)
           .get({
             success: res => {
               console.log(res.data.error)
               this.setData({
                 ['subject[' + list + ']']: res.data,
               })
               if (res.data.error == false) {
                 error = error + 1
                 this.setData({
                   error: Number(error)
                 })
               }
               if (res.data.right == false) {
                 right = right + 1
                 this.setData({
                   right: Number(right)
                 })
               }
             }
           })
       }
      }, 2000)
       
 
     

  })
  
      })


  },


// 5.替换用户数据
user_subject:function(){
  
 
},

  popop_d() {
    this.setData({
      popup: true
    })
  },

  // 点击答题卡关闭图标，关闭答题卡popup
  popup_close() {
    let popup = this.data.popup
    this.setData({
      popup: false
    })
  },
  model() {
    let model = this.data.model
    this.setData({
      model: false
    })
  },


  // 【背题】模式切换
  switch ({
      detail
    }) {
    // 需要手动对 checked 状态进行更新
    this.setData({
      checked: detail,
      popup: false
    });

  },

  // 用户点击【收藏】，更新全题库信息。
  star(e) {
    console.log(e.target.id)
    let openId = wx.getStorageSync('openId')
    if (e.target.id.indexOf("+") == -1) {
      var _id = openId + '+' + e.target.id
    } else {
      var _id = e.target.id
    }
    let subject = this.data.subject
    let index = this.data.index
    this.setData({
      ['subject[' + index + '].star']: !subject[index].star,
    })
    console.log(_id)

    db.collection('subject-all').doc(_id).set({
      data: {
        star: subject[index].star,
        analysis: subject[index].analysis,
        answer: subject[index].answer,
        user_answer:subject[index].user_answer,
        chapters: subject[index].chapters,
        difficulty: subject[index].difficulty,
        option: subject[index].option,
        subject: subject[index].subject,
        title: subject[index].title,
        type: subject[index].type,
        right: subject[index].right,
        error: subject[index].error,
        details: subject[index].details,
      },
    })





  },

  //【切题处理】开始滑动---------------------------------------------------------------------
  touchstart: function (e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY
    })
  },

  // 【切题处理】滑动角度限制
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 / Math,atan()返回数据的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI)
  },
  //答题卡跳转
  open(e) {
    // console.log(e.target.id)
    this.setData({
      index: Number(e.target.id),
      popup: false
    })
  },

  //【切题处理】滑结束事件处理
  tochend(e) {
    let {
      startX,
      startY
    } = this.data;
    let slidingRange = 45; //
    let touchMoveX = e.changedTouches[0].clientX;
    let touchMoveY = e.changedTouches[0].clientY;
    let index = this.data.index
    let angle = this.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    });
    //为了方便计算取绝对值判断
    if (Math.abs(angle) > slidingRange && touchMoveY < startY) {
      // 向上滑动

    };
    if (Math.abs(angle) > slidingRange && touchMoveY > startY) {
      // 向下滑动

    };


    // 向右滑动事件，切换到上一题，第一题停止切换。
    if (Math.abs(angle) < 45 && touchMoveX > startX) {
      // 向右滑动
      if (index == 0) {
        this.setData({
          index: 0
        })
      } else {
        this.setData({
          index: index - 1
        })
      }
    };

    // 向左滑动屏幕事件，切换到下一题
    if (Math.abs(angle) < 45 && touchMoveX < startX) {
      // 向左滑动
      let length = this.data.subject.length
      let index = this.data.index
      // console.log(index)
      if ((index + 1) < length) {
        this.setData({
          index: index + 1,
        })
      } else {
        this.setData({
          index: index,
        })
      }


    }
  },
})